<template>
    <div class="container">
        <div class="container-header">Online Judge</div>
        <div class="container-body">
            <div class="container-login">
                <NForm ref="loginRef" :model="loginModel" :rules="loginRules" label-placement="left" label-width="auto"
                    require-mark-placement="right-hanging">
                    <NFormItem label="账号" path="userCode">
                        <NInput v-model:value="loginModel.userCode" placeholder="请输入账号" />
                    </NFormItem>
                    <NFormItem label="密码" path="password">
                        <NInput v-model:value="loginModel.password" placeholder="请输入密码" type="password" />
                    </NFormItem>
                    <NFormItem>
                        <NButton class="login-button" type="primary" attr-type="submit" @click="handleLogin" size="large"
                            :loading="loginLoading" block>
                            登录
                        </NButton>
                    </NFormItem>
                </NForm>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { userApi } from '@/api'
import { useRouter } from 'vue-router';

const message = window["$message"];
const router = useRouter();
const loginRules = {
    userCode: {
        required: true,
        message: "请输入账号",
        trigger: ["input", "blur"],
    },
    password: {
        required: true,
        message: "请输入密码",
        trigger: ["input", "blur"],
    },
};

const loginLoading = ref(false);
const loginRef = ref();
const loginModel = ref({ userCode: '', password: '' });

const handleLogin = () => {
    loginRef.value
        ?.validate((errors) => {
            if (errors) {
                return;
            }
            loginLoading.value = true;
            userApi.login(loginModel.value).then((res) => {
                if (res.code === 200) {
                    message && message.success("登录成功");
                    router.push({ name: 'first' })
                }
            }).finally(() => {
                loginLoading.value = false;
            });
        });
}
</script>

<style scoped lang="less">
.container-header {
    height: 100px;
    line-height: 100px;
    text-align: center;
    font-size: 24px;
    font-weight: bold;
}

.container-body {
    display: flex;
    justify-content: center;

    .container-login {
        width: 400px;

        .login-button {
            width: 100px;
            margin: 0 auto;
        }
    }
}
</style>